<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/27
 * Time: 17:29
 */
namespace app\admin\controller;
use app\admin\model\AdminActionLogModel;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\Recycle;
use app\admin\validate\AdminValidate;
use app\common\controller\BackendController;
use app\admin\model\Admin as AdminModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;
use util\ArrayUtil;
use util\CommonUtil;

class Admin extends BackendController
{
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        if($this->request->isAjax()){
            $this->model = AdminModel::instance();
            list($where,$sort,$order,$page,$limit) = $this->model->buildParams($this->request);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->with('ParentAdmin')
                ->visible(['ParentAdmin'=>['username']])
                ->where($where)
                ->page($page,$limit)
                ->order($sort,$order)
                ->select();
            $this->success('查询成功','',['list'=>$list,'total'=>$total]);
        }
        return view();
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            !isset($data['status']) && $data['status'] = 0;
            if(!AdminValidate::instance()->scene('add')->check($data)){
                $this->error(AdminValidate::instance()->getError());
            }
            $res = AdminModel::create($data,['username','nickname','phone','email','password','parent_id','status','create_time']);
            if(!$res){
                $this->error('添加失败');
            }
            AdminActionLogModel::logAdd('添加管理员','username:'.$data['username']);
            $this->success('添加成功');
        }
        View::assign('parent_info',$this->auth->getAdmin());
        return view('edit');
    }
    /**
     * @param null $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id = null){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            !isset($data['status']) && $data['status'] = 0;
            if(!AdminValidate::instance()->scene('edit')->check($data)){
                $this->error(AdminValidate::instance()->getError());
            }
            $res = AdminModel::update($data,[],['id','username','nickname','phone','email','password','parent_id','status','update_time']);
            if(!$res){
                $this->error('更新失败');
            }
            AdminActionLogModel::logAdd('更新管理员','id:'.$data['id']);
            $this->success('更新成功');
        }
        if(!$id){
            $this->error('id不能为空!');
        }
        $info = AdminModel::find($id);
        $parent_info = AdminModel::find($info['parent_id']);
        View::assign('info',$info);
        View::assign('parent_info',$parent_info);
        return view();
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(){
        $ids = $this->request->param('ids/a');
        if(empty($ids)){
            $this->error('删除的数据不能为空！');
        }
        $admin_list = AdminModel::select($ids);
        $del_arr = [];
        foreach ($admin_list as $admin){
            $tmp = [
                'object_id'=>$admin['id'],
                'table_name'=>'admin',
                'name'=>$admin['username'],
                'admin_id'=>$this->auth->id
            ];
            $del_arr[] = $tmp;
        }
        try {
            Db::transaction(function () use ($ids, $del_arr) {
                $res = AdminModel::destroy($ids);
                if (!$res) {
                    throw new Exception('删除失败！', 401);
                }
                if (!Recycle::instance()->saveAll($del_arr)) {
                    throw new Exception('删除失败！', 402);
                }
            });
            AdminActionLogModel::logAdd('删除管理员','ids:'.json_encode($ids));
            $this->success('删除成功');
        }catch (Exception $e){
            $this->error('删除失败');
        }
    }

    public function status(){
        $ids = $this->request->param('ids/a');
        $status = $this->request->param('status/d');
        if(empty($ids)){
            $this->error('更新的数据不能为空！');
        }
        $res = AdminModel::update(['status'=>$status],[
            ['id','in',$ids]
        ],['status']);
        if(!$res){
            $this->error('更新失败');
        }
        AdminActionLogModel::logAdd('更新管理员状态','ids:'.json_encode($ids).',status:'.$status);
        $this->success('更新成功');
    }
    /**
     * @param null $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function auth($id = null){
        if($this->request->isPost()){
            $data = $this->request->post('post');
            if(!isset($data['group_ids'])){
                $data['group_ids'] = [];
            }
            if($data['admin_id'] == $this->auth->getRootId()){
                $this->error("默认管理员无法被授权！");
            }
            try{
                Db::transaction(function ()use ($data){
                    $del_res = AuthGroupAccess::destroy(['admin_id'=>$data['admin_id']]);
                    if(!$del_res){
                        throw new Exception('授权失败！',401);
                    }
                    if(empty($data['group_ids'])){
                        return true;
                    }
                    $add_list = [];
                    foreach ($data['group_ids'] as $group_id){
                        $tmp = [
                            'admin_id'=>$data['admin_id'],
                            'group_id'=>$group_id
                        ];
                        $add_list[] = $tmp;
                    }
                    $save_res = AuthGroupAccess::instance()->saveAll($add_list);
                    if(!$save_res){
                        throw new Exception('授权失败！',402);
                    }
                    return true;
                });
                AdminActionLogModel::logAdd('授权管理员','id:'.$data['admin_id'].',group:'.$data['group_ids']);
                $this->success("授权成功");
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
        }
        $group_list = AuthGroup::instance()->where('admin_id',$this->auth->id)->select();
        $admin_group_list = $this->auth->getGroup($id);
        $group_ids = ArrayUtil::instance()->array_extract($admin_group_list,'id');
        foreach ($group_list as &$info) {
            in_array($info['id'], $group_ids) ? $info['active'] = true :  $info['active'] = false;
        }
        View::assign('group_list',$group_list);
        return view();
    }

    public function info(){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            if(!AdminValidate::instance()->scene('edit')->check($data)){
                $this->error(AdminValidate::instance()->getError());
            }
            $res = AdminModel::update($data,[],['id','nickname','phone','email','update_time']);
            if(!$res){
                $this->error('更新失败');
            }
            AdminActionLogModel::logAdd('更新管理员','id:'.$data['id']);
            $this->success('更新成功');
        }
        View::assign('info',$this->auth->getAdmin());
        return view();
    }
    public function password(){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            $rule = [
                'oldpassword'=>'old_password',
                'repassword'=>'confirm_password'
            ];
            $data = CommonUtil::instance()->paramFieldChange($rule,$data);
            if(!AdminValidate::instance()->scene('edit_password')->check($data)){
                $this->error(AdminValidate::instance()->getError());
            }
            $res = AdminModel::update($data,[],['id','password','update_time']);
            if(!$res){
                $this->error('修改密码失败');
            }
            clearLoginSession();
            AdminActionLogModel::logAdd('修改管理员密码','id:'.$data['id'].',password'.$data['password']);
            $this->success('修改密码成功');
        }
        View::assign('info',$this->auth->getAdmin());
        return view();
    }
    public function clearCache(){
        Cache::clear();
        AdminActionLogModel::logAdd('清除缓存');
        $this->success('清除成功!');
    }
}